package com.example.graduatetest.activitys;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProviders;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.baidu.geofence.GeoFence;
import com.baidu.geofence.GeoFenceClient;
import com.baidu.geofence.GeoFenceListener;
import com.baidu.geofence.model.DPoint;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.DotOptions;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.example.graduatetest.R;
import com.example.graduatetest.bean.Classes;
import com.example.graduatetest.bean.Score;
import com.example.graduatetest.databinding.ActivityFindCardBinding;
import com.example.graduatetest.utils.Base64Util;
import com.example.graduatetest.utils.Constant;
import com.example.graduatetest.utils.GsonUtils;
import com.example.graduatetest.utils.HttpUtil;
import com.example.graduatetest.view.model.AddClassViewModel;
import com.example.graduatetest.view.model.FindCardViewModel;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FindCardActivity extends AppCompatActivity{
    private ActivityFindCardBinding binding;
    private FindCardViewModel findCardViewModel;
    private String result;
    private Bitmap bp;
    private String imagePath;
    //记录课程号
    private String  class_id;
    private int Photo_ALBUM = 1, CAMERA = 2;
    private Handler handler = new Handler();
    private boolean isFaceTrue = false;
    private Activity activity;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_card);

        //隐藏ActionBar
        if(getSupportActionBar() != null){
            ActionBar actionBar = getSupportActionBar();
            actionBar.hide();
        }
        //设置bitmap
        bp = null;

        //在使用SDK各组件之前初始化context信息，传入ApplicationContext
        SDKInitializer.initialize(getApplicationContext());
        activity = this;

        //自4.3.0起，百度地图SDK所有接口均支持百度坐标和国测局坐标，用此方法设置您使用的坐标类型.
        //包括BD09LL和GCJ02两种坐标，默认是BD09LL坐标。
        SDKInitializer.setCoordType(CoordType.BD09LL);

        binding = DataBindingUtil.setContentView(this,R.layout.activity_find_card);

        //接受Intent传来的数据
        Intent intent = getIntent();
        class_id = intent.getStringExtra("class_number");

        //LiveData
        findCardViewModel = ViewModelProviders.of(this).get(FindCardViewModel.class);
        binding.setFindCardViewModel(findCardViewModel);
        binding.setLifecycleOwner(this);
        findCardViewModel.init(this,binding,class_id);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.e("haha","onActivityResult");
        if(requestCode == CAMERA){

            imagePath = findCardViewModel.getImagePath();
            class_id = findCardViewModel.getClassNumber();
            // 相册选择图片
            bp = Constant.getImage(imagePath);
            //  iv_picture.setImageBitmap(bp);
            if(bp != null){
                runThread(class_id,this); //开启线程，传入图片
            }

        }

    }

    void runThread(final String class_number, final Activity activity) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = Constant.SEARCHURL;
                try {
                    byte[] bytes1 = Constant.getBytesByBitmap(bp);
                    //    byte[] bytes1 = FileUtil.readFileByBytes(ImagePath);
                    String image1 = Base64Util.encode(bytes1);

                    Map<String, Object> map = new HashMap<>();
                    map.put("image", image1);
                    map.put("liveness_control", "NORMAL");
                    map.put("group_id_list", class_number);
                    map.put("image_type", "BASE64");
                    map.put("quality_control", "LOW");

                    String param = GsonUtils.toJson(map);

                    // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
                    String accessToken = Constant.getAuth(Constant.clientId, Constant.clientSecret);

                    //24.389d01070c6f5e977e418e98c764db2b.2592000.1640850821.282335-25255846
                    result = HttpUtil.post(url, accessToken, "application/json", param);
                    Log.e("haha" , result);

                    if(result.contains("SUCCESS")){
                        JSONObject jsonObject = new JSONObject(result);
                        jsonObject = jsonObject.getJSONObject("result");
                        JSONArray jsonArray = jsonObject.getJSONArray("user_list");
                        jsonObject = jsonArray.getJSONObject(0);
                        double score = jsonObject.getDouble("score");
                        if(score >= 78){
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    findCardViewModel.changeText("打卡");
                                    Toast.makeText(activity,"人脸识别成功",Toast.LENGTH_SHORT).show();
                                }
                            });
                        }else{
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(activity,"人脸匹配失败",Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                    }else{
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(activity,"出现未知错误",Toast.LENGTH_SHORT).show();
                            }
                        });
                    }


                } catch (Exception e) {
                    Log.i("错误", "hahaha");
                    e.printStackTrace();
                }
            }
        }).start();
    }


}



